<template>
  <div class="ar-main" id="ar-main">

    <div class="user-info" v-show="user.accountId">
      <div class="user-info-left">
        <img class="avatar" :src="user.avatar ? user.avatar : defaultAvatar" @click="link2InfoPage">
      </div>

      <div class="user-info-middle">
        <div class="name-gender">
          <span class="nickname">{{user.nickname}}</span>
          <mu-badge :color="user.gender == 1 ? '#3cb2e2' : '#f878a8'" :content="genderStr" />
        </div>

        <div class="tag-list">
          <mu-badge class="tag-item-margin" v-for="(tag,index) in user.tagList" :primary="index%2===0" :secondary="index%2===1" :content="tag.content"
            :key="index" />
        </div>

        <div class="user-score">
          <star-rating :show-rating="false" :increment="0.01" :rating="user.score" :star-size="20" read-only></star-rating>
        </div>
      </div>

      <div class="user-info-right">
        <div class="button" @click="makeEvaluation(user.accountId)">
          <img src="../assets/images/write_eval_icon.png" class="eval-icon" alt=""> 去评价
        </div>
      </div>

    </div>

    <div class="evaluation-box" id="evaluation-con" v-show="user.accountId">
      <!--<div v-for='(item,index) in evaluateList' :key="item.id" class="evaluation-item" v-bind:style="{ top: getRandomLocation() , left: getRandomLocation() }">
                {{item.content}}
              </div>-->
    </div>

    <div class="button-box">

      <!--<div class="button" @click="getLocation">
                获取<br/>位置
              </div>-->

      <div class="accost" v-show="user.accountId">
        我想认识TA
        <div class="button" @click="offlineAccost">
          线下
          <br/>搭讪
        </div>
      </div>

      <label for="filechooser" class="button2" @click="setPhotoType">
        拍照
        <br/>识别
      </label>

      <div class="desc">
        对准你感兴趣的人
      </div>
    </div>

    <input id="filechooser" type="file" accept="image/*;" capture="camera" style="display:none;" />

    <mu-dialog :open="confirmDialog" @close="closeDialog">
      线下搭讪需要花费{{user.secretSignalPrice}}元，获取暗号之后可以直接凭暗号当面与对方搭讪，你确定要消费吗？
      <mu-flat-button slot="actions" primary @click="closeDialog" label="取消" />
      <mu-flat-button slot="actions" primary @click="purchaseSignal" label="确定" />
    </mu-dialog>

    <mu-dialog :open="signalDialog" @close="closeDialog">
      <div v-if="user.spareUser === 1">
        此用户暂不接受线下搭讪，你可以先关注或评价TA，给TA留个印象，祝你好运!
      </div>
      <div v-else>
        TA 的搭讪暗号是：<strong>{{user.secretSignal}}</strong>。请直接凭暗号当面与TA搭讪，祝您好运！
      </div>
      <mu-flat-button slot="actions" primary @click="closeDialog" label="确定" />
    </mu-dialog>

  </div>
</template>

<script>
  import mHeader from '../components/header'
  import util from '../util/util.js'
  import EXIF from 'exif-js'
  import defaultAvatar from '../assets/images/default_avatar.png'

  export default {
    name: 'arsocial',
    components: {
      mHeader
    },
    data() {
      return {
        defaultAvatar,
        accountId: null,
        user: {},
        evaluationPageNo: 1,
        evaluateList: {},
        confirmDialog: false,
        signalDialog: false,
        latitude: '',
        longitude: '',
      }
    },

    computed: {
      genderStr: function () {
        if (this.user.gender === 1) {
          return '男';
        } else if (this.user.gender === 0) {
          return '女';
        } else {
          return '未知';
        }
      },
      // bgStyle: function () {
      //   return {
      //     // backgroundImage: 'url(../assets/images/ar_bg.jpg)'
      //     backgroundImage: 'url(arBg)'
      //   };
      // }
    },

    methods: {

      bindUploadImgEvent() {
        let _this = this;
        let filechooser = document.getElementById('filechooser');
        filechooser.onchange = function () {
          let file = this.files[0];

          // 图片方向角
          var Orientation = null;

          if (file) {
            // 接受 jpeg, jpg, png 类型的图片
            if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) {
              return util.toast('不支持的文件格式');
            }
            //获取照片方向角属性
            EXIF.getData(file, function () {
              EXIF.getAllTags(this);
              Orientation = EXIF.getTag(this, 'Orientation');
              console.log('1. orientation = ' + Orientation + ' , date = ' + new Date());
            });
          }
          var reader = new FileReader();
          _this.$store.dispatch('showLoading');
          // console.log('3. readAsDataURL' + ' , date = ' + new Date());
          reader.readAsDataURL(file);
          reader.onload = function (e) {
            var image = new Image();
            // console.log('4. image start load' + ' , date = ' + new Date());
            image.src = e.target.result;
            image.onload = function () {
              // console.log('5. image over load' + ' , date = ' + new Date());
              var canvas = document.createElement("canvas");
              var ctx = canvas.getContext("2d");

              const maxH = 800;
              if (image.height > maxH) {
                image.width *= maxH / image.height;
                image.height = maxH;
              }
              canvas.width = image.width;
              canvas.height = image.height;
              ctx.drawImage(image, 0, 0, image.width, image.height);

              var base64 = null;
              console.log('2. orientation = ' + Orientation);
              if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                var width = this.naturalWidth;
                var height = this.naturalHeight;
                switch (Orientation) {
                  case 6: //需要顺时针90度旋转
                    // canvas.width = height;
                    // canvas.height = width;

                    canvas.width = image.height;
                    canvas.height = image.width;
                    ctx.rotate(90 * Math.PI / 180);
                    ctx.drawImage(this, 0, -height);
                    break;
                  case 8: //需要逆时针90度旋转
                    // canvas.width = height;
                    // canvas.height = width;

                    canvas.width = image.height;
                    canvas.height = image.width;
                    ctx.rotate(-90 * Math.PI / 180);
                    ctx.drawImage(this, -width, 0);
                    break;
                  case 3: //需要180度旋转
                    ctx.rotate(180 * Math.PI / 180);
                    ctx.drawImage(this, -width, -height);
                    break;
                }
              }
              // console.log('6. canvas.toDataURL start ' + ' , date = ' + new Date());
              base64 = canvas.toDataURL('image/jpeg', 0.92);
              // console.log('7. canvas.toDataURL over ' + ' , date = ' + new Date());

              _this.setImg(base64);
              _this.uploadImg(base64);
            };
          };
        };
      },

      setImg(dataUrl) {
        let bg = document.getElementById('ar-main');
        bg.style.backgroundImage = "url(" + dataUrl + ")";
        console.log('setImg over');
      },

      uploadImg(dataUrl) {
        console.log('latitude: ' + this.latitude);
        console.log('longitude: ' + this.longitude);
        let _this = this;
        const blob = this.dataURLtoBlob(dataUrl);
        const formData = new FormData();
        formData.append('file', blob);
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          //服务器连接已建立
          // if (xhr.readyState === 1) {
          //   _this.$store.dispatch('showLoading');
          // }

          if (xhr.readyState === 4) {
            _this.$store.dispatch('hideLoading');
            // console.log('8. response ' + ' , date = ' + new Date());

            // document.getElementById('filechooser')
            if (xhr.status === 200) {
              // 上传成功，获取到结果 results
              console.log(xhr.responseText);
              let response = JSON.parse(xhr.responseText);
              util.toast(response.msg);
              if (response.code === '0') {
                if (response.data.user != null) {
                  _this.user = response.data.user;
                  _this.getEvaluationList();
                } else {
                  _this.user = {};
                  _this.evaluationList = {};
                  util.toast('该用户还没在平台注册信息哦');
                }
              }

              if (response.code !== '0') {
                _this.user = {};
                _this.evaluationList = {};
              }

              console.log(_this.user);
              // _this.getUserInfo();
            } else {
              // 上传失败
              util.toast('网络异常');
            }
          }
        };

        // let url = 'http://120.24.89.166:520/ar-social/api/scan/user/others?lat=' + latitude + '&lng=' + longitude;
        let url = util.getHost() + '/ar-social/api/scan/user/others?lat=' + this.latitude + '&lng=' + this.longitude;
        console.log(url);
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Authorization', this.$store.state.token);
        xhr.send(formData);
      },

      dataURLtoBlob(dataURL) {
        console.log('dataURLtoBlob');
        let binaryString = atob(dataURL.split(',')[1]);
        let arrayBuffer = new ArrayBuffer(binaryString.length);
        let intArray = new Uint8Array(arrayBuffer);
        let mime = dataURL.split(',')[0].match(/:(.*?);/)[1]

        for (let i = 0, j = binaryString.length; i < j; i++) {
          intArray[i] = binaryString.charCodeAt(i);
        }

        let data = [intArray];
        let result = new Blob(data, {
          type: mime
        });
        console.log(result);
        return result;
      },

      getEvaluationList: function () {
        console.log('getEvaluationList, pageNo = ' + this.evaluationPageNo);
        let _this = this;
        const formData = new FormData();
        formData.append('page', this.evaluationPageNo);

        let xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              // 上传成功，获取到结果 results
              let response = JSON.parse(xhr.responseText);
              console.log(response);
              if (response.code === '0') {
                _this.evaluateList = response.data.evaluateList;
                if (_this.evaluateList >= 10) {
                  _this.evaluationPageNo++;
                } else {
                  _this.evaluationPageNo = 1;
                }
              }
            }
          }
        };
        // let url = 'http://120.24.89.166:520/ar-social/api/user/' + this.user.accountId + '/evaluates';
        let url = util.getHost() + '/ar-social/api/user/' + this.user.accountId + '/evaluates';
        xhr.open('GET', url, true);
        xhr.setRequestHeader('Authorization', this.$store.state.token);
        xhr.send(formData);
      },

      addEvaluation(content) {
        let x = this.getRandomLocation();
        let y = this.getRandomLocation();

        let dd = document.createElement('div');
        dd.style.position = 'absolute';
        dd.style.left = x;
        dd.style.top = y;
        dd.style.color = 'white';
        dd.style.backgroundColor = 'rgba(0, 0, 0, 0.4)';
        dd.style.padding = '4px 8px';
        dd.style.borderRadius = '4px';
        dd.innerHTML = content;

        document.getElementById('evaluation-con').appendChild(dd);
      },

      //获取标签的随机位置
      getRandomLocation() {
        let num;
        while (true) {
          num = Math.random() * 100;
          if (num >= 10 && num <= 80) {
            break;
          }
        }
        return parseInt(num) + '%';
      },

      link2InfoPage() {
        // if (!this.accountId) return;
        this.$router.push({
          name: 'UserInformation',
          params: {
            accountId: this.user.accountId
          }
        });
      },

      //获取地理位置
      getLocation() {
        let _this = this;
        var options = {
          enableHighAccuracy: true //boolean 是否要求高精度的地理信息，默认为false
        }

        function onError(err) {
          console.log('getLocation ERROR(' + err.code + '): ' + err.message)
          _this.latitude = '';
          _this.longitude = '';
        }

        function onSuccess(position) {
          var crd = position.coords;
          _this.latitude = crd.latitude;
          _this.longitude = crd.longitude;
          console.log('latitude: ' + crd.latitude);
          console.log('longitude: ' + crd.longitude);
        }

        console.log("geolocation");
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
        } else {
          //浏览器不支持geolocation
          console.log("浏览器不支持!");
        }
      },

      offlineAccost() {
        let _user = this.user;
        if (_user === null || _user === {}) return;

        //如果是假用户
        if (_user.spareUser === 1) {
          this.signalDialog = true;
          return;
        }

        //如果价格不为零，先显示确认窗口
        if (_user.secretSignalPrice === 0) {
          this.signalDialog = true;
        } else {
          this.confirmDialog = true;
        }
      },

      closeDialog() {
        this.confirmDialog = false;
        this.signalDialog = false;
      },

      purchaseSignal() {
        var _this = this;

        this.$http.post('order', {
          accountId: _this.user.accountId,
          price: _this.user.secretSignalPrice,
          type: 8
        }).then(
          function (response) {
            if (response.data.code === '0') {
              console.log('creat order success');
              _this.pay(response.data.data.sn);
            }
          }
        ).catch(
          function (error) {
            _this.closeDialog()
          }
        );
      },

      pay(orderId) {
        var _this = this;
        console.log('pay');
        this.$http.post('order/' + orderId + '/balance', {})
          .then(
            function (response) {
              _this.closeDialog()
              if (response.data.code === '0') {
                util.toast('购买成功');
                _this.user.secretSignalPrice = 0;
                _this.user.secretSignal = response.data.data.user.secretSignal;
                _this.signalDialog = true;
              }
            }
          ).catch(
            function (error) {
              _this.closeDialog()
            }
          );
      },

      setPhotoType() {
        console.log('setPhotoType type=3');
        var url = 'jsbridge://setSelectType?type=3';
        // var url = 'jsbridge://setSelectType?type=1';
        var iframe = document.createElement('iframe');
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        console.log('setPhotoType over');
        setTimeout(function () {
          iframe.remove();
        }, 100);
      },

      makeEvaluation(_accountId) {
        this.$router.push({
          name: 'MakeEvaluation',
          params: {
            accountId: _accountId,
          }
        });
      },

      setBg() {
        let gender = this.$store.state.myInfo.gender;
        let mCount = 8;
        let fCount = 6;
        let index;
        let pic;
        console.log(gender);
        if (gender === 0) { //女用户
          index = parseInt(Math.random() * mCount);
          pic = 'm' + index + '.jpg';
        } else { //男用户或未知性别
          index = parseInt(Math.random() * fCount);
          pic = 'f' + index + '.jpg';
        }

        // let photoURL = '/static/img/ar_bg/f1.jpg';
        let photoURL = '/static/img/ar_bg/' + pic;
        // console.log(photoURL);
        let bg = document.getElementById('ar-main');
        bg.style.backgroundImage = 'url(' + photoURL + ')';
      },
    },

    watch: {
      evaluateList: function (newValue) {
        console.log(newValue.length);
        for (var index = 0; index < newValue.length; index++) {
          this.addEvaluation(newValue[index].content);
        }
      }
    },

    mounted() {
      //因为开启了 keep-alive，用 @change 绑定事件的话，会发生的问题是事件绑定了很多次，
      //解决办法是在 mounted 中绑定一次
      this.bindUploadImgEvent();
      this.setBg();
      // this.getLocation();
    },
    activated() {
      this.setPhotoType();
      this.getLocation();
    }

  }

</script>


<style lang="less" scoped>
  .ar-main {
    /*position: relative;*/
    display: flex;
    flex-direction: column;
    /*justify-content: center;*/
    position: absolute;
    width: 100%;
    top: 48px;
    bottom: 48px;
    left: 0px;
    /*height: 100%; 用这种方式在手机QQ浏览器上不能自适应高度*/
    /* 加载背景图 */
    /*background-image: url(../assets/images/ar_bg.jpg);*/
    /*background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490538835&di=6a151de7508d0006c0bbbdf37844ce3f&imgtype=jpg&er=1&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8601a18b87d6277f01ef72382a381f30e924fc35.jpg);*/
    /* 背景图垂直、水平均居中 */
    background-position: center center;
    /* 背景图不平铺 */
    background-repeat: no-repeat;
    /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
    background-attachment: fixed;
    /* 让背景图基于容器大小伸缩 */
    background-size: cover;
    /* 设置背景颜色，背景图加载过程中会显示背景色 */
    background-color: #464646;
  }

  .user-info {
    padding: 16px 0;
    background-color: rgba(255, 255, 255, 0.5);
    display: flex;
    align-items: center;
    .avatar {
      border-radius: 50%;
      border: 1px solid #9c55a1;
      width: 64px;
      height: 64px;
    }
    &-left {
      margin: 0 24px;
    }
    &-middle {
      flex: 1;
      .name-gender {
        display: flex;
        align-items: center;
        font-size: 16px;
        color: #333333;
        .nickname {
          margin-right: 8px;
        }
      }
      .tag-list {
        margin-top: 2px;
        max-height: 44px;
        overflow: hidden;
        .badge {
          margin: 0 2px;
        }
      }
      .user-score {
        margin-top: 2px;
      }
    }
    &-right {
      margin: 0 24px;
      .button {
        display: flex;
        align-items: center;
        padding: 3px 8px 3px 4px;
        border-radius: 4px;
        background-color: rgba(0, 0, 0, 0.6);
        font-size: 12px;
        color: white;
        .eval-icon {
          width: 16px;
          margin: 0 2px;
        }
      }
    }
  }

  .button-box {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    bottom: 6%;
    color: white;
    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      /*padding: 4px;*/
      width: 60px;
      height: 60px;
      /*margin-top: 4px;*/
      margin: 0 auto;
      border-radius: 50%;
      background-color: #9c55a1;
      border: 4px solid rgba(256, 256, 256, 0.2);
      /*border: 4px solid rgba(156, 85, 161, 0.5);*/
      color: white;
    }
    .button2 {
      background-image: url(../assets/images/recognize_btn.png);
      /*background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490538835&di=6a151de7508d0006c0bbbdf37844ce3f&imgtype=jpg&er=1&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F8601a18b87d6277f01ef72382a381f30e924fc35.jpg);*/
      /* 背景图垂直、水平均居中 */
      background-position: center center;
      /* 背景图不平铺 */
      background-repeat: no-repeat;
      /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
      /*background-attachment: fixed;*/
      /* 让背景图基于容器大小伸缩 */
      background-size: cover;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 140px;
      height: 140px;
      font-size: 12px;
      /*padding: 4px;
      /*margin-top: 4px;*/
      /*margin: 0 auto;*/
      /*margin-top: 8px;*/
      /*border: 4px solid rgba(156, 85, 161, 0.5);*/
      color: white;
      /*text-align: center;*/
    }
    .desc {
      padding: 8px 24px;
      background-image: url(../assets/images/recognize_desc_bg.png);
      background-size: cover;
      background-position: center center;
      background-repeat: no-repeat;
    }
  }

  .evaluation-box {
    /*background-color: rgba(255, 222, 222, 0.5);*/
    flex: 1;
    position: relative;
    /*color: white;*/
    .evaluation-item {
      color: white;
      font-size: 16px;
      position: absolute;
      padding: 4px 8px;
      border-radius: 4px;
      background-color: rgba(0, 0, 0, 0.4);
    }
  }

</style>
